#!/usr/bin/python
# -*- coding: UTF-8 -*-

import uiautomator2 as u2
from lib.func import isLinuxSystem, isWindowsSystem
import math, time, os, logging, sys
from exception.error import AlreadyLoginError, DouyinRuntimeError
from threading import Thread

class Base():
    def __init__(self, sn):
        self.sn = sn 
        self.device = u2.connect_usb(sn)
        
        self.info = info = self.device.info
        self.device_info = self.device.device_info
        self.ppx = "{0}-{1}".format(info['displayWidth'], info['displayHeight'])

    def log(self, log, *args, **kwargs):
        return logging.info(log, args, kwargs)

    def _device_info(self):
        return self.device.info

    def is_screen_on(self):
        return self._device_info()['screenOn']

    def screen_on(self):
        return self.device.screen_on()

    def screen_off(self):
        return self.device.screen_off()

    def press(self, key):
        return self.device.press(key)

    def press_home(self):
        logging.warning("按压home")
        return self.press("home")
        self.sleep(2)

    def press_back(self):
        self.press("back")
        self.sleep(1)

    def press_enter(self):
        return self.press("enter")

    def press_delete(self):
        return self.press("delete")

    def click(self, x, y):
        return self.device.click(x, y)

    def double_click(self, x, y, time=0.1):
        return self.device.double_click(x, y, time)

    def long_click(self, x, y, time=0.5):
        return self.device.long_click(x, y, time)

    def swipe(self, sx, sy, ex, ey, time=0.5):
        return self.device.swipe(sx, sy, ex, ey, time)

    def swipe_up(self, times=1):
        #self.swipe(540, 1320, 540, 540, 0.5)
        for i in range(times):
            self.swipe(540, 1320, 540, 540, 0.3)
            self.sleep(1)

    def swipe_up_fast(self, times=1):
           for i in range(times):
            self.swipe(540, 1320, 540, 540, 0.1)
            self.sleep(1)

    def swipe_down(self):
        #self.swipe(540, 540, 540, 1620, 0.5)
        return self.swipe(540, 540, 540, 1620, 0.2)

    def swipe_right(self):
        return self.swipe(600, 500, 10, 500, 0.1)

    def swipe_left(self):
        return self.swipe(10, 500, 600, 500, 0.1)

    def current_app(self):
        return self.device.current_app()

    def wait_activity(self, activity, timeout):
        return self.device.wait_activity(activity, timeout=10)

    def app_stop_all(self):
        self.press_home()
        self.sleep(3)
        if self.device_info['brand'] == "Xiaomi":
            logging.warning("开始杀死小米所有应用")
            self.press("menu")
            self.sleep(1)
            self.device(resourceId="com.android.systemui:id/clearAnimView").click_exists(timeout=2)
        else:
            logging.warning("开始杀死锤子所有应用")
            self.press(187)
            self.sleep(1)
            self.device(resourceId="com.android.systemui:id/recents_clear_button").click_exists(timeout=2)

        self.sleep(2)
        self.press_home()

    def sleep(self, misc=0.5):
        return time.sleep(misc)

    def app_start(self, pkg_name,
                  activity=None,
                  extras={},
                  wait=True,
                  stop=False,
                  unlock=False):
        return self.device.app_start(pkg_name,
                  activity=None,
                  extras={},
                  wait=True,
                  stop=False,
                  unlock=False)

    def screenshot(self, path=None):
        if path == None:
            path = "/tmp/{}.jpg".format(self.sn)
        """
        暂时先用adb命令
        """
        return self.get_screencap(path)
        
        self.device.screenshot(path)
        return path

    def get_screencap(self, path):
        """ 截屏并下载到本地 """
        logging.warning("正在截屏")

        self.device.shell("screencap -p /sdcard/screen.png")

        cmd_pull = "adb -s {0} pull /sdcard/screen.png {1}".format(self.sn, path)
        os.system(cmd_pull)

        return path

class Douyin(Base):
    def __init__(self, sn):
        super(Douyin, self).__init__(sn)
        grepcmd = "findstr" if isWindowsSystem() else "grep"
        cmd = "adb -s {0} shell pm dump com.ss.android.ugc.aweme | {1} 'versionName'".format(self.sn, grepcmd)
        version = os.popen(cmd).read()
        self.version = version.strip().split("=")[1]
        if self.version != "5.5.1":
            raise RuntimeError("版本不是5.5.1")
        #self.register_watcheres()

        #Thread(target=self.verify_thread_1).start()
        #Thread(target=self.verify_thread_2).start()

    def unlock_swipe(self):
        self.swipe(640, 1320, 640, 140, 0.1)

    def unlock(self):
        logging.warning("开始解锁")
        if not self.is_screen_on():
            self.screen_on()
            self.sleep(1)
            self.unlock_swipe()
            self.sleep(1)

    def resetIp(self):
        logging.warning("开关飞行模式")
        self.device.shell("settings put global airplane_mode_on 1")
        self.sleep(5)
        self.device.shell("settings put global airplane_mode_on 0")
        self.sleep(1)
        
    def goto_top_right(self):
        for i in range(6):
            self.swipe_right()
        self.sleep()

    def get_douyin_pos_and_click(self, index):
        """
        根据编号打开抖音
        """
        if self.device_info['brand'] == "Xiaomi":
            logging.warning("是小米手机")
            return self.device(text="{}".format(index+1)).click_exists(timeout=3)
        else:
            DouyinIconWidth  = 240
            DouyinIconHeight = 340
            first_pos   = {"x":150, "y":250} #第一个抖音分身的位置

            pos = (
                first_pos['x'] + DouyinIconWidth * (index%4),
                first_pos['y'] + DouyinIconHeight * math.floor(index/4)
            )

            self.click(pos[0], pos[1])
            logging.warning('正在打开第 {0} 个抖音 {1}, {2}'.format(index+1, pos[0], pos[1]))

    def write_text(self, text):
        """
        输入文字
        """
        self.device.set_fastinput_ime(True) # 切换成FastInputIME输入法
        self.sleep(1)
        self.device.set_fastinput_ime(True) # 切换成FastInputIME输入法
        self.sleep(1)
        self.device.send_keys(text) # adb广播输入
        self.sleep(1)
        self.press_back()

    def check_voice_permission(self):
        """
        检测录音权限
        """
        logging.warning("正在检测摄像头权限弹窗")
        clicked = self.device(text='允许').click_exists(timeout=5)
        self.sleep(2)
        logging.warning("正在检测录音权限弹窗")
        clicked = self.device(text='允许').click_exists(timeout=5)
        self.device(text="上传").click()

    def click_city(self):
        logging.warning('点击城市名')
        """
        城市id可能是
        5.2.0       com.ss.android.ugc.aweme:id/cme
        5.1.1       com.ss.android.ugc.aweme:id/cqa
        """
        resp1 = self.device(resourceId="com.ss.android.ugc.aweme:id/cpo").click_exists(timeout=10)
        #resp = resp1 or resp2
        if not resp1:
            return False

        logging.warning("检查地域切换弹窗")
        self.device(text="取消").click_exists(timeout=5)

        logging.warning("开始上划")
        self.swipe_up()

        return True

    def check_is_image_verify(self):
        """
        判断是否出验证了
        """
        if self.device(text="点击选中两个相同形状的物体").exists(timeout=2):
            return True

        return self.device(text="点击选中两个相同形状的物体").exists(timeout=2)

    def check_is_not_login(self):
        resp = self.device(text='我').click_exists(timeout=5)
        self.reportClick(resp, "没有找到我的按钮，应该不在抖音主界面")

        resp1 = self.device(text="密码登录").exists(timeout=3)
        resp2 = self.device(text="其他登录方式").exists(timeout=3)

        if resp2:
            self.device(text="手机验证码或密码登录").click_exists(timeout=2)

        return resp1 or resp2


    def first_open(self):
        self.sleep(10)
        #while self.current_app()['package'] != "com.ss.android.ugc.aweme":
        #    logging.warning("等待进入抖音")

        if self.device(textContains="封禁").exists():
            raise RuntimeError("账号被封禁")
        
        logging.warning("判断授权位置")
        if self.device(resourceId="com.lbe.security.miui:id/event_title").exists(timeout=10):
            self.device(resourceId="android:id/button2").click_exists(timeout=3)

        for i in range(6):
            self.check_window()
        
        logging.warning("检测完毕")
        if not self.click_city():
            logging.warning("没有找到城市按钮")
            self.first_open()

    def open_douyin_by_packname(self, package):
        self.unlock()
        self.sleep(1)
        self.press_home()
        self.sleep(1)
        self.app_stop_all()
        self.resetIp()
        self.app_start(package)

        self.first_open()
        logging.warning("进入主页")
        return True

    def open_douyin(self, index):
        """
        打开抖音,传入参数是正常编号，比如1就是1
        """
        self.unlock()
        self.sleep(1)
        self.press_home()
        self.sleep(1)
        self.app_stop_all()
        self.sleep(1)
        self.goto_top_right()
        self.sleep(1)
        self.resetIp()

        """ 打开第 index 个抖音 """
        logging.warning("打开第{}个抖音".format(index))

        if not self.get_douyin_pos_and_click(index-1):
            return False

        self.device(text="继续播放").click_exists(timeout=8)
        self.raiseErrorWapper(self.device.wait_activity("com.ss.android.ugc.aweme.main.MainActivity", timeout=60), "60s还未进入主页，退出")

        logging.warning("进入主页")
        return True

    def get_video_pos(self, index):
        """ 获得视频位置 """
        VIDEO_WIDTH  = 270
        VIDEO_HEIGHT = 265

        first_video = {"x":130, "y":480} #第一个视频的位置

        pos = (
            first_video["x"] + VIDEO_WIDTH * (index%4),
            first_video["y"] + VIDEO_HEIGHT * math.floor(index/4)
        )

        return pos

    def click_video(self, index):
        pos = self.get_video_pos(index)
        self.click(pos[0], pos[1])
        self.sleep(1.5)

    def click_first_video(self):
        """
        点击第一个视频
        """
        self.device(resourceId="com.ss.android.ugc.aweme:id/b17", instance=0).click_exists(timeout=2)

    """
    def uploadFile(self, path, title, app_id):
        self.device.healthcheck()
        if self.open_douyin(app_id):
            self.videoSdk.pushVedio(path)
            for i in range(3):
                self.videoSdk.upload(title)
        return False
    """

    def raiseErrorWapper(self, status, error_info):
        if status == True:
            return
        
        logging.warning("raiseErrorWapper:{}".format(error_info))
        self.press_home()
        self.app_stop_all()
        raise DouyinRuntimeError(error_info)

    def reportClick(self, resp, message):
        if not resp:
            raise RuntimeError(message)

    def check_window(self):
        logging.warning("检测滑动")
        if self.device(text="滑动查看更多").exists():
            self.swipe_up()

        resp = self.device(text="同意").click_exists()
        logging.warning("检测用户政策弹窗:{}".format(resp))

        resp = self.device(text="以后再说").click_exists()
        logging.warning("检测新版本呢弹窗:{}".format(resp))

        logging.warning("检测流量弹窗")
        if self.device(text="继续播放").exists():
            self.device(text="本月非Wi-Fi下自动播放").click_exists(timeout=2)
            self.device(text="继续播放").click_exists(timeout=2)

        logging.warning("检测联系人弹窗")
        if self.device(text="发现通讯录好友").exists():
            self.device(text="取消").click_exists(timeout=2)

        self.device(text="我知道了").click_exists(timeout=2)
            
        self.sleep(1)

    def click_resource_and_check(self, resourceId, msg, timeout=5):
        logging.warning("寻找resourceId:\t{}\t{}".format(resourceId, msg))
        self.reportClick(self.device(resourceId=resourceId).click_exists(timeout=timeout), msg)

    def click_text_and_check(self, text, timeout=5):
        logging.warning("寻找text"+text)
        self.reportClick(self.device(text=text).click_exists(timeout=timeout), text)

    def zan(self):
        self.click_resource_and_check("com.ss.android.ugc.aweme:id/bre", "找不到点赞图标")
        self.sleep(2)

    def comment(self, text):
        self.click_resource_and_check("com.ss.android.ugc.aweme", "找不到回复图标")
        self.sleep(2)
        self.device(resourceId="com.ss.android.ugc.aweme:id/a5e").set_text(text)
        self.sleep(2)
        self.click_resource_and_check("com.ss.android.ugc.aweme:id/alf", "找不到评论并转发图标")
        self.click_resource_and_check("com.ss.android.ugc.aweme:id/a5h", "找不到发送图标")
        self.sleep(2)
        self.click_resource_and_check("com.ss.android.ugc.aweme:id/lk", "找不到关闭按钮")
        self.sleep(2)



    def verify_thread_1(self):
        logging.warning("检测验证码1")
        while True:
            if self.device(text="点击选中两个相同形状的物体").exists(timeout=30):
                logging.warning("弹验证码了")
                return True

    def verify_thread_2(self):
        logging.warning("检测验证码2")
        while True:
            if self.device(text="点击选中两个相同形状的物体").exists(timeout=30):
                logging.warning("弹验证码了")
                return True

